package com.whmnx.chitchat.main;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.qcloud.tim.uikit.component.UnreadCountTextView;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.base.BaseApplication;
import com.whmnx.chitchat.bean.LoginBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.fragment.BookFragment;
import com.whmnx.chitchat.fragment.MessageFragment;
import com.whmnx.chitchat.fragment.MyFragment;
import com.whmnx.chitchat.fragment.MyFragment2;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.utils.HubConnectionUtils;
import com.whmnx.chitchat.utils.ReliableClient;
import com.whmnx.chitchat.utils.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.whmnx.chitchat.fragment.MessageFragment.FOLLOW;

/**
 * @author Administrator
 */
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private ArrayList<Fragment> mFragments;
    public MessageFragment homeFragment = new MessageFragment();
    public BookFragment messageFragment = new BookFragment();
    public MyFragment myFragment = new MyFragment();

    private RadioGroup mRg_content_fragment;
    private Fragment currentFragment;
    private long exitTime;
    public static MainActivity mContext;
    private RadioButton mRb_main_chat;
    private UnreadCountTextView mMsgUnread;
    public static ReliableClient reliableClient;
    String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        BaseApplication.getInstance().addActvity(this);
        mContext = MainActivity.this;
        initFragments();
        initView();
        initListener();
        reliableClient = new ReliableClient(Constants.CODEBUILD,this);
      //  HubConnectionUtils.connection();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("UserID",SPUtil.getString(Constants.USERID));
        params.put("DeviceToken",SPUtil.getString("deviceToken"));
        params.put("MoveType","1");
        HttpClient.get(this, Constants.UPDATEUSERDEVICETOKEN, params,new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.MSGNUM)) {
                String num = messageEvent.getMessageValue();
                int nums =  Integer.parseInt(num);
                if (nums > 0) {
                    mMsgUnread.setVisibility(View.VISIBLE);
                    if (nums > 99){
                        mMsgUnread.setText("99+");
                    }else {
                        mMsgUnread.setText(num);
                    }

                }else {
                    mMsgUnread.setVisibility(View.GONE);
                }
            }
        }
    }

    private void initFragments() {
        mFragments = new ArrayList<>();
        mFragments.add(homeFragment);
        mFragments.add(messageFragment);
        mFragments.add(myFragment);
    }

    private void initView() {
        mRg_content_fragment = (RadioGroup) findViewById(R.id.rg_content_fragment);
        mRb_main_chat = (RadioButton) findViewById(R.id.rb_main_chat);
        mMsgUnread = findViewById(R.id.unread_msg_number);
        mRg_content_fragment.setOnCheckedChangeListener(this);
        replaceFragment("home");
    }

    private void replaceFragment(String tag) {
        if (currentFragment != null) {
            Log.i("MainActivity", tag + "-----1");
            getSupportFragmentManager().beginTransaction().hide(currentFragment).commit();
        }
        currentFragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (currentFragment == null) {
            switch (tag) {
                case "home":
                    currentFragment = new MessageFragment();
                    break;
                case "conversation":
                    currentFragment = new BookFragment();
                    break;
                case "mine":
                    currentFragment = new MyFragment();
                    break;
                default:
            }
            Log.i("MainActivity", tag + "-----2");
            getSupportFragmentManager().beginTransaction().add(R.id.fl_container, currentFragment, tag).commit();
        } else {
            getSupportFragmentManager().beginTransaction().show(currentFragment).commit();
        }
    }


    private void initListener() {
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.WRITE_CALENDAR
                        , Manifest.permission.CHANGE_WIFI_STATE,Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                .subscribe(granted -> {
                    if (granted) {
                        //  Toast.makeText(MainActivity.this, "同意权限", Toast.LENGTH_SHORT).show();
                    } else {
                        //  Toast.makeText(MainActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                    }
                });
            }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int position = group.indexOfChild(group.findViewById(checkedId));
        switch (position){
            case 0:
                replaceFragment("home");
                break;
            case 1:
                replaceFragment("conversation");
                break;
            case 2:
                replaceFragment("mine");
                break;
            default:
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        }
        else{
             BaseApplication.getInstance().exit();
             finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(FOLLOW, false)) {
         //   mRb_main_chat.setChecked(true);
        }
    }

    @Override
    protected void onDestroy() {//释放资源
        HubConnectionUtils.isConnect = false;
        if (HubConnectionUtils.hubConnection != null)
            HubConnectionUtils.hubConnection.stop();
            HubConnectionUtils.hubConnection = null;
            super.onDestroy();
    }
}